<template>
  <div>
    <el-tree
      :data="data"
      default-expand-all
      node-key="id"
      :expand-on-click-node="false"
      :props="defaultProps"
    >
      <!--  default-expand-all（展示所有子节点）  expand-on-click-node （表示点击当前行取消展开下拉） -->
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>
            <img v-if="data.picUrl" :src="data.picUrl" class="custom-tree-node-img" />
            {{ node.label }}
            <el-tag
              v-if="data.level!=3&&data.title"
              :type="data.level==0?'danger':(data.level==1?'warning':(data.level==2?'success':''))"
            >
              <!-- 这个是三元函数表达式 -->
              <!-- {{node.level==1?'一级':(node.level==2?'二级':(node.level==3?'三级':''))}} -->
              <!-- 这个是使用事件的方法 -->
              {{treeLevel(data.level)}}
            </el-tag>
          </span>
          <span>
            <el-button v-if="data.level!=2" type="primary" @click="Add(data)" round>添加</el-button>
            <el-button v-if="data.level!=3" type="warning" @click="Edit(data)" round>编辑</el-button>
            <el-button
              v-if="data.level==2||Showa(data)"
              type="danger"
              @click="Delete(node,data)"
              round
            >删除</el-button>
          </span>
        </span>
      </template>
    </el-tree>
    <!-- 修改弹框 -->
    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item label="类目名称" prop="title">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="类目图片">
          <el-upload
            v-model="form.picUrl"
            class="avatar-uploader"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :headers="token"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.picUrl" :src="form.picUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible=false">取消</el-button>
          <el-button type="primary" @click="fangdou">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {post} from "@/util/http";
// import {post,host,upload} from "../../../util/http";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import cookies from "js-cookie";
import { debounce } from "@/fangdou/fangdou";//防抖fangdou
export default {
  components: {
    Plus,
  },
  data() {
    return {
      token: cookies.get("token"),
      defaultProps: {
        children: "childrenList",
        label: "title",
      },
      data: [], //列表数据
      dialogFormVisible: false, //布尔值
      title: "", //弹框标题
      id: "",
      parentId: "",
      form: {
        title: "", //标题
        picUrl: "", //类名图片
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入类目名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.listData();
  },
  methods: {
    // 弹框提交
    subMit(ruleFormRef) {
      this.$refs.ruleFormRef.validate((ref) => {
        //表单的规则验证
        if (ref) {
          if (this.title == "创建") {
            let data = {
              _gp: "admin.category",
              _mt: "create",
              title: this.form.title,
            };
             post(data)
              .then((res) => {
                if (200 == res.data.errno) {
                  this.listData();
                  this.dialogFormVisible = false;
                  ElMessage.success("创建成功");
                } else {
                  ElMessage.warning(res.data.errmsg);
                }
              })
              .catch((err) => {
                ElMessage.error(err.data.errmsg);
              });
          } else {
            let data = {
              _gp: "admin.category",
              _mt: "update",
              id: this.id,
              title: this.form.title,
              parentId: this.parentId,
            };
             post(data)
              .then((res) => {
                if (200 == res.data.errno) {
                  this.form = {
                    title: "",
                    picUrl: "",
                  };
                  this.listData();

                  this.dialogFormVisible = false;
                  ElMessage.success("编辑成功");
                } else {
                  ElMessage.warning(res.data.errmsg);
                }
              })
              .catch((err) => {
                ElMessage.error(err.data.errmsg);
              });
          }
        } else {
          ElMessage.warning("带星号的必填信息不能为空!");
        }
      });
    },
    fangdou: debounce(function () {
      this.subMit();
    }),
    // 添加
    Add() {
      this.title = "创建";
      this.form = {
        title: "",
        picUrl: "",
      };
      this.dialogFormVisible = true;
    },
    // 编辑
    Edit(e) {
      console.log(e, "bji笔记编辑");
      this.title = "编辑";
      this.id = e.id;
      this.parentId = e.parentId;
      this.form = {
        title: e.title,
        picUrl: e.picUrl,
      };
      this.dialogFormVisible = true;
    },
    // 删除
    Delete(node,e) {
        console.log(node,"删除123");
        console.log(e,"删除");
      this.$confirm("确定要删除吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          let data = {
            _gp: "admin.category",
            _mt: "delete",
            id: e.id,
          };
           post(data).then((res) => {
            if (200 == res.data.errno) {
              this.data.splice(e.data, 1);
              ElMessage.success("删除成功!");
              this.listData();
            }
          });
        })
        .catch(() => {
          ElMessage.info("已取消删除");
        });
    },
    // 判断添加按钮是否显示
    Showa(e) {
      if (!e.childrenList) {
        //如果对象的childrenList不存在，就返回一个true
        return true;
      }
    },
    // 等级事件
    treeLevel(e) {
      switch (e) {
        case 0:
          return "一级";
          break;
        case 1:
          return "二级";
          break;
        case 2:
          return "三级";
          break;

        default:
          break;
      }
    },
    // 类目列表
    listData() {
      let data = {
        _gp: "admin.category",
        _mt: "list",
      };
       post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            this.list = res.data.data.items;
            this.data = [
              {
                childrenList: res.data.data.items,
                title: "全部类目",
                level: 3,
              },
            ];
          } else {
            ElMessage.warning(res.data.errmsg);
          }
        })
        .catch((err) => {
          ElMessage.error(err.data.errmsg);
        });
    },
  },
};
</script>
<style lang="less" scoped>
div /deep/ .el-tree-node__content {
  ///deep/加深度，使子元素的等级优先
  height: 40px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .custom-tree-node-img {
    width: 30px;
    height: 30px;
  }
}
// 弹框上传图片
.avatar-uploader /deep/ .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader /deep/ .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>